<?php
/**
 * 
 * @author zjx
 * 备注：
 * $this->getStage() 和 $this->setStage() 方法只用于存取当前应用的持久数据
 * storage相关方法用于存取通用应用的持久数据
 */
class WebUserD extends CWebUser {
	const STORAGE_KEY = 'data';
	const PREFIX_KEY_FRONT='_front';
	const PREFIX_KEY_ADMIN='_admin';
	public $usertype = 'front';
	protected $key = '';
	protected $appId;
	protected $prefixKey;
	public function init(){
		parent::init();
		$this->setApp ();
	}
	/**
	 * 设置应用
	 * @param string $type
	 */
	protected function setApp() {
		if ($this->usertype == 'front') {
			$this->appId = Yii::app ()->params ['frontpassportid'];
			$this->key = Yii::app ()->params ['frontpassportkey'];
			$this->prefixKey =self::PREFIX_KEY_FRONT;
		} else if ($this->usertype == 'admin') {
			$this->appId = Yii::app ()->params ['adminpassportid'];
			$this->key = Yii::app ()->params ['adminpassportkey'];
			$this->prefixKey = self::PREFIX_KEY_ADMIN;
		} else {
			throw new Exception ( 'WebUserD 实例化类型错误' );
		}
	}
	/**
	 * 重写登录后的方法
	 * @param string    $fromCookie
	 */
	protected function afterLogin($fromCookie) {
		parent::afterLogin ( $fromCookie );
		try {
			
			//$data = $this->getAttributes ();
			//if (! isset ( $data [self::STORAGE_KEY] [$this->prefixKey] ) || ! (is_array ( $data [self::STORAGE_KEY] [$this->prefixKey] ) && count ( $data [self::STORAGE_KEY] [$this->prefixKey] ) > 0)) {
				$data = $this->initAttributes ();
			//}
			$this->setState ( $this->usertype, $data );
			//$this->clearOtherSession();
		} catch ( Exception $e ) {
			throw $e;
		}
	}
	/**
	 * 清除前台用户缓存
	 * return array 
	 */
	protected function clearOtherSession(){
		/**
		 * 正式上线后补写该段代码
		 */
		$flag=array(false, false, false);
		if ($this->usertype == 'admin'){

			if(!Yii::app()->frontuser->isGuest){
				Yii::app()->frontuser->logout();
				$flag[0]=true;//前台用户注销成功标识
				$tickets = Yii::app()->frontuser->getState('tickets') . '^|^' . $_SERVER['REQUEST_TIME'];//生成tickets;
				$h=new HttpClientD(Yii::app()->params['giftUrl']."/out.php?tickets=".$tickets);
				$cookiesString=session_name().'='.session_id();
				$h->setCookiesAsString($cookiesString);
				$h->open();
				$response=$h->excute();
				if($response==='logout succssfully'){
					$flag[1]=true;
				}else{
					$flag[1]=false;
				}
				$apiObj = new MallApi();
				$flag[2]=$apiObj->logout();
			}
		}else if($this->usertype == 'front'){
			if(!Yii::app()->admin->isGuest){
				ob_start();
				Yii::app()->admin->logout();
				$content = ob_get_contents();
    			ob_end_clean();
			}
		}
		
		/* if ($this->usertype == 'front') {
			Yii::app()->admin->logout();
		} else if ($this->usertype == 'admin') {
			Yii::app()->frontuser->logout();
			$tickets = Yii::app()->frontuser->getState('tickets') . '^|^' . $_SERVER['REQUEST_TIME'];
			$tickets = XxteaD::encrypt($tickets, Yii::app()->params['frontpassportkey']);
			echo "<iframe src='".Yii::app()->params['giftUrl']."/out.php?tickets=".$tickets."' width='0' height='0' frameborder='0'></iframe>";
		} */
		
	}
	/**
	 * 只获取passport相关的Session数据
	 * @param $key 如果传入了key，则返回key对应的值
	 */
	public function getPassportData($key = null) {
		$data = $this->getState ( $this->usertype );
		unset ( $data [self::STORAGE_KEY] );
		return is_null ( $key ) ? $data : (isset ( $data [$key] ) ? $data [$key] : NULL);
	}
	/***
	 * 只针对passport相关数据设置本地session
	 */
	public function setPassportData($key, $val) {
		$data = $this->getState ( $this->usertype );
		if ($key != self::STORAGE_KEY && isset ( $data [$key] )) {
			$data [$key] = $val;
			$this->setState ( $this->usertype, $data );
			return true;
		}
		return false;
	}
	/**
	 * 通过$key获取同步缓存的数据
	 * @param string    $key    键值
	 * @return string
	 */
	public function getStorage($key) {
		$data = $this->getStorages ();
		return isset ( $data [$key] ) ? $data [$key] : NULL;
	}
	
	/**
	 * 获取所有同步缓存的数据
	 * @return array
	 */
	public function getStorages() {
		$data = $this->getState ( $this->usertype );
		return $data [self::STORAGE_KEY] [$this->prefixKey];
	}
	
	/**
	 * 通过$key=>$val设置同步缓存的数据
	 * @param string    $key            键值
	 * @param mix       $value          数据
	 * @param mix       $defaultValue   默认数据
	 * @return void 
	 */
	public function setStorage($key, $value, $defaultValue = null) {
		$data = $this->getState ( $this->usertype );
		$data [self::STORAGE_KEY] [$this->prefixKey] [$key] = is_null ( $value ) ? $defaultValue : $value;
		$this->setAllStorages ( $data );
	}
	
	/**
	 * 设置所有同步的数据
	 * @param array     $data   数据
	 * @return void
	 */
	public function setStorages(array $data) {
		$d=$this->getState($this->usertype);
		$tmp=array_merge($d[self::STORAGE_KEY][$this->prefixKey],$data);
        $d[self::STORAGE_KEY][$this->prefixKey]=$tmp;
        //file_put_contents('/home/wwwroot/lq/zz.log', var_export($d,true));
		$this->setAllStorages($d);
	}
	
	protected function setAllStorages(array $data) {
		try {
			$rs=$this->setAttributes ( $data [self::STORAGE_KEY][$this->prefixKey]  );
            if($rs) 
                $this->setState ( $this->usertype, $data );
		} catch ( Exception $e ) {
			throw $e;
		}
	}
	/**
	 * 设置所有属性到缓存
	 * @return array
	 */
	protected function initAttributes() {
		try {
			$account = $this->generateAttributes ();
			//$data = $this->getAttributes ();
			//$data [self::STORAGE_KEY] = $account;
			$data = $account;
			$this->setAttributes ( $data,false );
			return $this->getAttributes ();
		} catch ( Exception $e ) {
			throw $e;
		}
	}
	
	/**
	 * 获取所有属性
	 * @return array
	 */
	protected function getAttributes() {
		try {
			/*
			$tickets = $this->getState ( 'tickets' );
			$obj_res = new Resposity ();
			$obj_res->cid = $this->appId;
			$obj_res->accounttype = $this->getState ( 'login_method' );
			$result = $obj_res->getUserAttributes ( $tickets );
			if(is_int($result)){
				throw new Exception ('错误代码: '.$result );
			}
			$result[self::STORAGE_KEY]= CJSON::decode ( $result[self::STORAGE_KEY] );
			return $result;
			*/
			$tickets = $this->getState ( 'tickets' );
			$p=new PassportApi($this->usertype);
			return $p->getPassportCachedUserDataByTickets($tickets);
		} catch ( Exception $e ) {
			throw $e;
		}
	}
	
	protected function setAttributes(array $data) {
		try {
			/*
			$tickets = $this->getState ( 'tickets' );
			$obj_res = new Resposity ();
			$obj_res->cid = $this->appId;
			$obj_res->accounttype = $this->getState ( 'login_method' );
			//array('_front);
			$rs = $obj_res->saveUserAttributes ( $tickets, $data );
			$arr = UtilD::parseResult ( $rs );
			if ($arr ['key'] == '1') {
				return true;
			} else {
				throw new Exception ( $arr ['keyMain'] );
			}
			*/
			$tickets = $this->getState ( 'tickets' );
			$p=new PassportApi($this->usertype);
			//file_put_contents('/home/wwwroot/lq/ss.log',var_export($data,true));
			$rs=$p->setPassportCachedUserData($tickets,$data);
			return $rs;
		} catch ( Exception $e ) {
			throw $e;
		}
	}
	/**生成数据**/
	protected function generateAttributes() {
		try {
			if ($this->usertype == 'front')
				return $this->generateFrontUserAttributes ();
			else if ($this->usertype == 'admin')
				return $this->generateAdminAttributes ();
			else
				throw new Exception ( '应用类型错误' );
		} catch ( Exception $e ) {
			throw $e;
		}
	}
	/**
	生成后台用户数据
	 **/
	protected function generateAdminAttributes() {
		$row = Admin::model ()->findByPk ( $this->getId () );
		$result_data = $row->getAttributes ();
		return $result_data;
	}
	//获取所有用户需要同步缓存的数据
	protected function generateFrontUserAttributes() {
		
		$user = new User ();
		$user_id = ( int ) $this->getId ();
		if ($user_id < 1) {
			throw new Exception ( "帐号已经离线" );
			return null; //return UtilD::handleResult ( 0, '帐号已经离线！' );
		}
		
		if ($this->getState('group_id') == '1') { //个人用户
			$model = new PersonalInfo();
			$row=$model->findByPk($user_id);
			$result=$row->getAttributes();
			isset($result['often_address']) && $result['often_address_name'] = Area::getAreaname($result['often_address']);
		} else if ($this->getState('group_id') == '2') {
			$row=$user->findByPk($user_id);
			$result=$row->getAttributes();
			$shop_id=$result['bind_shop'];
			if($shop_id!=''){
				$shop=new Shop();
				$row2=$shop->findByPk($shop_id);
				if(!is_null($row2) && $row2->bind_status==2){
/* 					$result['shop_name']=$row2->shop_name;
					$result['shop_logo']=$row2->logo;
					$result['shop_address']=$row2->address;
					$result['bind_status']=$row2->bind_status;
					$result['area_code']=$row2->area_code; */
					$result['cat_code']=$row2->cat_code;
					if($row2->user_id!=$user_id){
						$row2->user_id=$user_id;
						$row2->save();
					}
				}else{
					$row->bind_shop='';
					$row->save();
					$result['bind_shop']='';
				}
			}
		} else {
			throw new Exception ( __CLASS__ . "=>" . __LINE__ . "异常错误" );
			return null; //return UtilD::handleResult ( 0, '帐号数据异常！' );
		}
		return $result;
	}
}

?>